<?php
namespace app\commands;
/**
 * Created by PhpStorm.
 * User: Egorka
 * Date: 11.08.2017
 * Time: 15:07
 */

use app\core\forms\user\UserForm;
use Yii;
use yii\base\Exception;
use app\core\services\user\UserManageService;
use yii\console\Controller;
use yii\helpers\ArrayHelper;

class UserController extends Controller
{
    private UserManageService $user_service;

    public function __construct($id, $module, UserManageService $user_service, $config = [])
    {
        parent::__construct($id, $module, $config);
        $this->user_service = $user_service;
    }


    /**
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function actionAdd(): void
    {
        $username = $this->prompt('Username:', ['required' => true]);
        $email    = $this->prompt('Email:', ['required' => true]);
        $password = $this->prompt('Password:', ['required' => true]);
        $role     = $this->select('Role:', ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description'));

        $form           = new UserForm();
        $form->username = $username;
        $form->email    = $email;
        $form->password = $password;
        $form->role     = $role;

        if ($form->validate()) {
            $this->user_service->create($form);
            $this->stdout('Done!' . PHP_EOL);

            return;
        }

        $this->stdout('Errors found!' . PHP_EOL);
        foreach ($form->errors as $error) {
            $this->stdout(is_string($error) ? $error : $error[0] . PHP_EOL);
        }
    }
}
